import { NextRequest, NextResponse } from 'next/server';
import path from 'path';
import { promises as fs } from 'fs';
import { parse } from 'csv-parse/sync';
import { getDb } from '@/lib/real-sqlite-database';

export async function POST(request: NextRequest) {
  const db = getDb();
  try {
    const { directory } = await request.json();
    
    // 1. 首先导入设备数据
    const specialties = ['配管专业', '仪表专业', '电气专业', '通信专业', '暖通专业'];
    for (const specialty of specialties) {
      const deviceFile = path.join(process.cwd(), directory, `设备表-${specialty}.csv`);
      if (await fs.stat(deviceFile).catch(() => null)) {
        const content = await fs.readFile(deviceFile, 'utf-8');
        const records = parse(content, { columns: true, skip_empty_lines: true });
        
        for (const record of records) {
          await db.insertDevice({
            name: record['设备名称'] || record['实体对象名称'],
            classification_name: record['分类名称'],
            classification_code: record['分类码'],
            specialty: specialty,
            sequence_number: record['序号']?.toString() || '',
            remarks: record['备注'] || ''
          });
        }
      }
    }
    
    // 2. 导入参数数据
    const parameterFiles = [
      { name: '属性表-基础参数表.csv', type: 'base' },
      { name: '属性表表.csv', type: 'position' },
      { name: '属性表-对象命名表.csv', type: 'naming' }
    ];
    
    for (const { name, type } of parameterFiles) {
      const paramFile = path.join(process.cwd(), directory, name);
      if (await fs.stat(paramFile).catch(() => null)) {
        const content = await fs.readFile(paramFile, 'utf-8');
        const records = parse(content, { columns: true, skip_empty_lines: true });
        
        for (const record of records) {
          const params = {
            parameter_name: record['参数名称'],
            data_type: record['数据类型'] || '',
            example_description: record['示例说明'] || '',
            measurement_class: record['计量分类'] || '',
            data_source: record['数据来源'] || '',
            is_required: record['是否必填'] === '是' ? 1 : 0
          };
          
          // 根据参数类型调用不同的保存方法
          switch (type) {
            case 'base':
              await db.saveBaseParameters(record['设备ID'], [params]);
              break;
            case 'position':
              await db.savePositionParameters(record['设备ID'], [params]);
              break;
            case 'naming':
              await db.saveNamingParameters(record['设备ID'], [params]);
              break;
          }
        }
      }
    }
    
    return NextResponse.json({ success: true, message: '数据导入成功' });
  } catch (error) {
    console.error('导入数据时出错:', error);
    return NextResponse.json({ 
      success: false, 
      error: `导入数据失败: ${error instanceof Error ? error.message : '未知错误'}`
    }, { status: 500 });
  } finally {
    db.close();
  }
} 